<?php

namespace app\http\exception;

use think\exception\Handle;
use think\facade\Log;

class ApiHandleException extends Handle {
    private $code;
    private $msg;
    private $httpCode = 200;

    /**
     * @Desc: 继承exception类
     *
     * @param \Exception $ex
     *
     *
     * @User: Randy_chen
     * @Date: 2019/5/16
     * @Time: 14:37
     */
    public function render(\Exception $ex) {
        if ($ex instanceof BaseException) {
            $this->code = $ex->code;
            $this->msg = $ex->msg;
            $this->httpCode = $ex->httpCode;
        } else {
            if (config('app.app_debug')) {
                return $this->show(1, $ex->getMessage(), []);
            }
            $this->httpCode = 500;
            return $this->show(1, $ex->getMessage(), []);
        }

        $message = "【文件】:{$ex->getFile()};【行号】: {$ex->getLine()}";
        $this->show($this->code, $this->msg, $message);
    }

    /**
     * 通用化API接口数据输出.
     *
     * @param int    $code     错误码
     * @param string $msg      错误返回码
     * @param string $message  异常提示
     * @param array  $data     数据
     * @param int    $httpCode http状态码
     *
     * @return mixed
     */
    public function show($code, $msg, $message = '', $data = [], $httpCode = 200) {
        $data = [
            'code'    => $code,
            'msg'     => $msg,
            'message' => $message,
            'data'    => $data,
        ];
        $httpCode = $httpCode ?: $this->httpCode;
        echo json_encode($data, JSON_UNESCAPED_UNICODE);
        exit;
    }

    /**
     * @Desc: 自定义错误日志
     *
     * @param \Exception $ex
     *
     * @User: Randy_chen
     * @Date: 2019/5/16
     * @Time: 14:38
     */
    private function recordErrorLog(\Exception $ex) {
        Log::init([
                      'type'  => 'File',
                      'path'  => LOG_PATH,
                      'level' => ['error'],
                  ]);
        Log::record($ex->getMessage(), 'error');
    }
}
